package com.atguigu.gulimall.product.service.impl;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.common.utils.Querys;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Querys<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> allList = baseMapper.selectList(null);
        //2.组装成父子的树形结构 找出级别不同的分类
        //找出一级分类
        List<CategoryEntity> leveMenue = allList.stream().filter(category ->
             category.getParentCid() == 0
        ).map(menue -> { menue.setChildren(getChildrens(menue,allList));
        return menue;} ).sorted((menue1, menue2) -> {
            //2菜单排序
            return (menue1.getSort() == null ? 0 : menue1.getSort() ) - (menue2.getSort() == null ? 0 : menue2.getSort()
            );
        }).collect(Collectors.toList());
        //再找子分类，这时候entity里面需要再加个属性list
        return leveMenue;
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> allList){
        //从allList找到 当前菜单root的子菜单，也就是当前菜单的id 等于 子菜单的parentId
        List<CategoryEntity> children = allList.stream().filter(list -> {
            return root.getCatId().equals(list.getParentCid());
        }).map(list -> {
            //1找到子菜单
            list.setChildren(getChildrens(list, allList));
            return list;
        }).sorted((menue1, menue2) -> {
                //2菜单排序
                return (menue1.getSort() == null ? 0 : menue1.getSort() ) - (menue2.getSort() == null ? 0 : menue2.getSort()
                );
        }).collect(Collectors.toList());
        return children;
    }

    @Override
    public void removeMenueByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public List<Long> findCatelogPath(Long catelogId) {
        List<Long> list = new ArrayList<>();
        while (catelogId > 0){
            CategoryEntity byId = this.getById(catelogId);
            if (byId != null && byId.getParentCid() > 0){
                list.add(catelogId);
                catelogId = byId.getParentCid();
                continue;
            }{
                list.add(catelogId);
                break;
            }
        }
        // 由高级别到低级别封装完整分类路径
        Collections.reverse(list);
        return list;
    }

    /**
     * 级联更新所有关联表的数据
     * @param category
     */
    @Override
    @Transactional
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
}